import {login} from '@/api/login';
import Cookies from 'js-cookie';

const state = {
    account: Cookies.get('overrun_service_account') || '',
    token: Cookies.get('overrun_service_token') || '',
    role_id: Cookies.get('overrun_service_role_id') || '',
    permissions: []
};

const getters = {
    isLogin: state => {
        let retn = false;
        if (state.token) {
            retn = true;
        }
        return retn;
    }
};

const actions = {
    login({commit}, data) {
        return new Promise((resolve, reject) => {
            login(data).then(res => {
                // console.log(res);
                const resdata = res.res;
                resdata.LoginName = data.username;
                if (resdata.LoginStatus == 'T') {
                    let role_id = resdata.role_id.role_id;
                    resdata.role_id = role_id;
                    commit('setUserData', resdata);
                }

                resolve(resdata);
            }).catch(error => {
                reject(error);
            });
        });
    },
    logout({commit}) {
        commit('removeUserData');
        commit('menu/invalidRoutes', null, {root: true});
    },
    // 获取我的权限
    getPermissions({state, commit}) {
        return new Promise(resolve => {
            // 通过 mock 获取权限
            resolve([]);
        });
    }
};

const mutations = {
    setUserData(state, data) {
        // console.log(data);
        Cookies.set('overrun_service_account', data.LoginName);
        Cookies.set('overrun_service_token', data.AutoLogin);
        Cookies.set('overrun_service_role_id', data.role_id);
        state.account = data.LoginName;
        state.token = data.AutoLogin;
        state.role_id = data.role_id;
    },
    removeUserData(state) {
        Cookies.remove('overrun_service_account');
        Cookies.remove('overrun_service_token');
        Cookies.remove('overrun_service_role_id');
        state.account = '';
        state.token = '';
        state.role_id = '';
    },
    setPermissions(state, permissions) {
        state.permissions = permissions;
    }
};

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
};
